﻿using System;

namespace IndexerStudy
{


    //索引器的使用
    //索引器其实本质上就是属性(Property)的一种特殊形式
    class Base1 {
        private int age = 100;
        private String text = "文本";
        private String[] names;

        public Base1(int size) {
            names = new string[size];
            for (int i = 0; i < names.Length; i++) {
                names[i] = "NAME:" + i;
            }
        }

        public int NamesLength {
            get{
                return names.Length;
               }
            

            
        }

        public String this[int index]
        {
            
            get {
                if (index >= 0 && index <= names.Length)
                {
                    return this.names[index];
                }
                else {
                    return "非法下标索引器失效";
                }
            }

            set {
                if (index >= 0 && index <= names.Length)
                {
                     this.names[index]=value;
                }
                else
                {
                    this.names[index] = "非法"; 
                }
            }
        }

        //通过往索引器中传递字符串(可为其他数据类型)
        public int this[String strIndex]
        {
            get {
                int index = 0;
                while (index < names.Length) {
                    if (names[index]==strIndex) {
                        return index;
                    }
                    index++;
                }
                return -1;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Base1 base1 = new Base1(5);
            for (int i = 0; i < base1.NamesLength; i++) {
                System.Console.Write(base1[i] + " ");
            }
            System.Console.WriteLine();
            System.Console.WriteLine("============");
            base1[4] = "jjj";

            System.Console.WriteLine(base1[4]+"  "+base1[7]);

            System.Console.WriteLine("============");

            System.Console.WriteLine(base1["NAME:3"]+"  "+base1["jjj"]);
        }
    }
}
